const fs = require('fs');
const path = require('path');

const args = process.argv.splice(2);
const command = args.shift();
const taskDescription = args.join(' ');
const file = path.join(__dirname, '/tasks.json');

switch (command) {
  case 'list':
    listTasks(file);
    break;

  case 'add':
    addTask(file, taskDescription);
    break;

  default:
    console.log('Users: ' + process.argv[0] + ' list|add [taskDescription]');
}

function listTasks(file) {
  loadOrInitialzeTaskArray(file, function (tasks) {
    for (const i in tasks) {
      console.log(tasks[i]);
    }
  });
}

function loadOrInitialzeTaskArray(file, cb) {
  const exists = fs.existsSync(file);
  if (exists) {
    fs.readFile(file, 'utf-8', function (err, data) {
      if (err) {
        throw err;
      }
      const text = data.toString();
      const tasks = JSON.parse(text || '[]');
      cb(tasks);
    });
  } else {
    cb([]);
  }
}

function addTask(file, taskDescription) {
  loadOrInitialzeTaskArray(file, function (tasks) {
    tasks.push(taskDescription);
    storeTasks(file, tasks);
  });
}

function storeTasks(file, tasks) {
  fs.writeFile(file, JSON.stringify(tasks), 'utf-8', function (err) {
    if (err) {
      throw err;
    }
    console.log('Saved.');
  });
}
